
<!DOCTYPE HTML>
<html>

	<head>
		<title>使用Selector API实现购物车客户端计算</title>
		<meta charset="utf-8" />
		<style>
			table {
				width: 600px;
				text-align: center;
				border-collapse: collapse;
				table-layout: fixed;
			}
			
			td,
			th {
				border: 1px solid black;
				
			}
			
			td[colspan="3"] {
				text-align: right;
			}
			/*tbody>tr>td:last-child{background-color:red}*/
			/*tfoot>tr>td:last-child{background-color:red}*/
		</style>
		<!--<script src="js/6_2.js"></script>-->
	</head>

	<body>
		<table id="data">
			<thead>
				<tr>
					<th>商品名称</th>
					<th>单价</th>
					<th>数量</th>
					<th>小计</th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<td>iPhone6</td>
					<td>&yen;4488</td>
					<td>
						<button>-</button>
						<!--this指当前事件所在的元素对象
		  何时使用: 如果事件处理中需要使用当前元素对象-->
						<span>1</span>
						<button>+</button>
					</td>
					<td>&yen;4488</td>
				</tr>
				<tr>
					<td>iPhone6 plus</td>
					<td>&yen;5288</td>
					<td>
						<button>-</button>
						<span>1</span>
						<button>+</button>
					</td>
					<td>&yen;5288</td>
				</tr>
				<tr>
					<td>iPad Air 2</td>
					<td>&yen;4288</td>
					<td>
						<button>-</button>
						<span>1</span>
						<button>+</button>
					</td>
					<td>&yen;4288</td>
				</tr>
			</tbody>
			<tfoot>
				<tr>
					<td colspan="3">Total: </td>
					<td id="total">&yen;0</td>
				</tr>
			</tfoot>
		</table>				
		<script type="text/javascript">
		    //按钮
			var buts=document.querySelectorAll("button");
			//数量
			var num=document.querySelectorAll("span");		
			var tbody=document.querySelector("tbody");
			var trs=tbody.querySelectorAll("tr");
			console.log(trs);
			console.log(buts);
			for(let i=0;i<buts.length;i++){
				buts[i].onclick=function(){
					if(this.innerHTML=="+"){
						//修改数量
						this.previousElementSibling.innerHTML=parseInt(this.previousElementSibling.innerHTML)+1;	
						//计算小计
						this.parentNode.nextElementSibling.innerHTML="&yen"+parseInt(this.parentNode.previousElementSibling.innerHTML.slice(1))*(this.previousElementSibling.innerHTML);												
						//计算总价
						allprice(1);
																						
					}else{
						if(this.nextElementSibling.innerHTML>1){
							this.nextElementSibling.innerHTML=parseInt(this.nextElementSibling.innerHTML)-1;							
						}
						this.parentNode.nextElementSibling.innerHTML="&yen"+parseInt(this.parentNode.previousElementSibling.innerHTML.slice(1))*(this.nextElementSibling.innerHTML);
						allprice(2);
					}
				}
			}
			
			function allprice(num){
				if(num==1){
					for(var m=0,sum=0;m<trs.length;m++){
							sum+=parseInt(trs[m].lastElementChild.innerHTML.slice(1));
						}
						total.innerHTML="&yen"+sum;
				}else{
					for(var m=0,sum=0;m<trs.length;m++){
							sum+=parseInt(trs[m].lastElementChild.innerHTML.slice(1));
						}
						total.innerHTML="&yen"+sum;
				}
			}
			
			allprice();
		</script>
	</body>

</html>